package com.tqz.juc.aqs;

import java.util.concurrent.Exchanger;

/**
 * 两个线程之间的交换.
 *
 * @author tianqingzhao
 * @since 2022/2/5 18:17
 */
public class ExchangerTest2 {
    private static Exchanger<String> exchanger = new Exchanger<>();
    static String goods = "电脑";
    static String money = "$4000";

    public static void main(String[] args) throws InterruptedException {

        System.out.println("准备交易，一手交钱一手交货...");
        // 卖家
        new Thread(() -> {
            System.out.println("卖家到了，已经准备好货：" + goods);
            try {
                // 如果另外一个线程没有调用 exchange方法，那么当前线程就会一直阻塞在这里
                String money = exchanger.exchange(goods);
                System.out.println("卖家收到钱：" + money);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(3000);

        // 买家
        new Thread(() -> {
            try {
                System.out.println("买家到了，已经准备好钱：" + money);
                // 如果另外一个线程没有调用 exchange方法，那么当前线程就会一直阻塞在这里
                String goods = exchanger.exchange(money);
                System.out.println("买家收到货：" + goods);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }
}
